﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
using YeqianFramework.common;
using YeqianFramework.config;

namespace YeqianFramework.core
{
	public enum YQFKContextStartupState
	{
		Start = 0,
		YQFKConfigLoadComplete = 1,
	}

	public class YQFKContext : MonoBehaviourSingleton<YQFKContext>
	{
		private YQFKContextStartupState status = YQFKContextStartupState.Start;

		public YQFKConfig YQFKConfig { get; private set; }
		protected override void Init()
		{

		}


		private Action<float, float> nextStep;
		private Action complete;

		/// <summary>
		/// 更新状态，执行回调<br/>
		/// 比如如果我完成了 YQFKConfigLoadComplete ，则执行<code>StatusUpdate(YQFKContextStartupState.YQFKConfigLoadComplete)</code>
		/// </summary>
		public void StatusUpdate(YQFKContextStartupState completeStatus)
		{
			status |= completeStatus;
			int maxVal = (int)Mathf.Pow(2, status.GetType().GetEnumNames().Length - 1) - 1;

			nextStep((int)status, maxVal);
			if ((int)status == maxVal)
			{
				YQLogCenter.Current.YQFKLog("框架初始化成功！");
				complete();
			}
		}

		private SynchronizationContext context;
		/// <summary>
		/// 启动框架（读取配置文档）
		/// </summary>
		/// <param name="yqfkConfigXmlPath">YQFKConfig.xml 的路径</param>
		/// <returns>是否初始化成功</returns>
		public YQFKContext StartUp(string yqfkConfigXmlPath, Action<float, float> nextStrpCallback, Action completeCallback)
		{
			nextStep = nextStrpCallback;
			complete = completeCallback;

			context = SynchronizationContext.Current;
			new Thread(new ParameterizedThreadStart(ReadConfig)).Start(yqfkConfigXmlPath);

			return Current;
		}

		private void ReadConfig(object state)
		{
			string yqfkConfigXmlPath = state as string;
			YQFKConfig config;
			try
			{
				config = XmlHelper.Xml2Object<YQFKConfig>(yqfkConfigXmlPath);
			}
			catch (Exception e)
			{
				YQLogCenter.Current.YQFKError(e.Message);
				throw;
			}

			context.Post(new SendOrPostCallback(ReadConfigCallback), config);
		}

		private void ReadConfigCallback(object yqfkConfig)
		{
			YQFKConfig = yqfkConfig as YQFKConfig;
			StatusUpdate(YQFKContextStartupState.YQFKConfigLoadComplete);
		}

		/// <summary>
		/// 关闭游戏
		/// </summary>
		public static void GameShutdown()
		{
#if UNITY_EDITOR
			EditorApplication.isPlaying = false;
#else
				Application.Quit();
#endif
		}

		private void Update()
		{
			if ((status & YQFKContextStartupState.YQFKConfigLoadComplete) == YQFKContextStartupState.YQFKConfigLoadComplete 
				&& Input.GetKeyDown(YQFKConfig.callDebugFieldKey))
			{
				UIDebugeField.Current.isActive = !UIDebugeField.Current.isActive;
				Debug.Log("切换显示 isDebugFieldActive：" + UIDebugeField.Current.isActive);
			}
		}
	}
}
